package com.rasenhund.android.grecorder.activity;

import java.util.ArrayList;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.rasenhund.android.grecorder.R;
import com.rasenhund.android.grecorder.adapter.HistoryListAdapter;
import com.rasenhund.android.grecorder.common.Const;
import com.rasenhund.android.grecorder.dao.RecordDao;
import com.rasenhund.android.grecorder.helper.DbHelper;
import com.rasenhund.android.grecorder.schema.StageRecord;

/**
 * 履歴一覧画面
 */
public class HistoryListActivity extends BaseActivity {
    @SuppressWarnings("unused")
    private static final String TAG = HistoryListActivity.class.getSimpleName();
    private final HistoryListActivity self = this;

    HistoryListAdapter mAdapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_history);

    }

    @Override
    protected void onResume() {
        super.onResume();

        initView();

    }

    /********************
     * EventListener
     ********************/

    /**
     * ListItem クリック時のイベントリスナ
     */
    final OnItemClickListener lstHistory_OnItemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {

            StageRecord record = mAdapter.getItem(pos);

            Intent intent = new Intent(self, HistoryDetailActivity.class);
            intent.putExtra(Const.KEY.KEY_ROWID, record.getRowId());
            startActivity(intent);

        }

    };

    /********************
     * Method
     ********************/
    /**
     * Viewの初期化
     */
    private void initView() {

        ArrayList<StageRecord> list = null;

        // 表示用データの取得
        DbHelper dbHelper = null;
        SQLiteDatabase db = null;

        try {

            dbHelper = new DbHelper(self);
            db = dbHelper.getWritableDatabase();
            RecordDao dao = new RecordDao(db);

            list = dao.selectAll(false);

        } finally {
            if (db.isOpen()) {
                db.close();
            }
        }

        // viewの初期化
        mAdapter = new HistoryListAdapter(self, list);

        ListView lstHistory = (ListView) findViewById(R.id.lstHistory);
        lstHistory.setOnItemClickListener(lstHistory_OnItemClickListener);
        lstHistory.setAdapter(mAdapter);

        // データがなければNo Dataを表示
        if (list.size() == 0) {
            TextView txtNoData = (TextView) findViewById(R.id.txtNoData);
            txtNoData.setVisibility(View.VISIBLE);
        }

    }

}
